import json
from datetime import datetime, timedelta

import cv2
import numpy as np
from flask import Blueprint, render_template, request, current_app

from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import CourseStandard, ActionInfo, KeyframeInfo, StandardResult, PoliceModels
from applications.schemas import StandardSchema, ActionSchema, KeyframeInfoSchema, PoliceOutSchema, StandardResultSchema
from applications.common.course.generate import CourseGenerator
from sqlalchemy import desc

course_standard_bp = Blueprint('courseStandard', __name__, url_prefix='/course/standard')


@course_standard_bp.get('/')
def main():
    return render_template('admin/course/action_standard/main.html')


@course_standard_bp.get('/data/course')
def data():
    # 获取请求参数
    course_name = xss_escape(request.args.get('course_name', type=str))

    # 查询参数构造
    mf = ModelFilter()
    if course_name:
        mf.contains(field_name="course_name", value=course_name)

    # orm查询
    # 使用分页获取data需要.items
    courses = CourseStandard.query.filter(mf.get_filter(model=CourseStandard)).filter_by(del_flag=0).with_entities(
        CourseStandard.course_id,
        CourseStandard.course_name,
        CourseStandard.course_description,
        CourseStandard.course_loadtime,
        CourseStandard.course_updatetime).layui_paginate()
    count = courses.total
    # 返回api
    return table_api(data=model_to_dicts(schema=StandardSchema, data=courses.items), count=count)


@course_standard_bp.get('/data/action/<int:course_id>')
def getActionsByCourseId(course_id):
    actions = ActionInfo.query.filter_by(course_id=course_id, del_flag=0).with_entities(ActionInfo.course_id,
                                                                                        ActionInfo.action_id,
                                                                                        ActionInfo.action_name,
                                                                                        ActionInfo.action_description,
                                                                                        ActionInfo.action_path,
                                                                                        ActionInfo.action_length,
                                                                                        ActionInfo.action_loadtime,
                                                                                        ActionInfo.action_updatetime,
                                                                                        ActionInfo.icon_path).all()
    actions = model_to_dicts(schema=ActionSchema, data=actions)
    res = {
        "msg": "查找动作成功",
        "code": 0,
        "success": True,
        "data": actions
    }
    return res


@course_standard_bp.get('/add/course')
def getAddCoursePage():
    return render_template('admin/course/action_standard/add.html')


@course_standard_bp.get('/add/action')
def getAddActionPage():
    return render_template('admin/course/action_standard/action/add.html')


@course_standard_bp.get('/cover/course')
def getCourseCover():
    return render_template('admin/course/action_standard/cover.html')


@course_standard_bp.get('/cover/action')
def getActionCover():
    return render_template('admin/course/action_standard/action/cover.html')


@course_standard_bp.post('/generate')
def generateKeyframe():
    try:
        data = request.json
        fileName = data['path']
        filePath = '.' + fileName.replace('_uploads/course_action/videos',
                                          current_app.config.get("UPLOADED_ACTION_DEST"))
    except:
        return fail_api(msg="关键帧生成参数错误")
    try:
        open(filePath, 'rb')
    except:
        return fail_api(msg="视频不存在")
    generator = CourseGenerator()
    generator.get_keyFrame(file_path=filePath)
    keyframes = generator.frame_info
    sk_list = generator.sk_list
    skeleton_path = generator.skeleton_path
    for key in keyframes:
        keyframes[key][2] = keyframes[key][2].tolist()
    res = {
        "msg": "生成关键帧成功！",
        "code": 0,
        "success": True,
        "data":
            {
                "keyframe_info": json.dumps(keyframes),
                "icon_path": generator.icon_path,
                "skeleton_path": skeleton_path
            }
    }
    return res


@course_standard_bp.post('/add/course')
def addCourse():
    try:
        data = request.json
        icon_path = data['course_icon']
        course_name = data['course_name']
        course_description = data['course_description']
        action_infos = data['action_infos']
    except KeyError:
        return fail_api(msg='课程参数缺失，请检查课程参数')

    # 尝试根据图片路径获取图片二进制文件
    try:
        with open('.' + icon_path.replace('_uploads/course_action/videos',
                                          current_app.config.get("UPLOADED_ACTION_DEST")), 'rb') as f:
            image_data = f.read()
    except FileNotFoundError:
        return fail_api(msg="找不到课程封面")

    # 新增课程
    courseStandard = CourseStandard(course_name=course_name,
                                    course_icon=image_data,
                                    course_description=course_description,
                                    icon_path=icon_path,
                                    del_flag=0)
    db.session.add(courseStandard)
    db.session.commit()

    # 新增课程完成后，为课程新增动作
    course_id = courseStandard.course_id

    for action_info in action_infos:
        try:
            action_name = action_info['action_name']
            action_icon_path = action_info['action_icon']
            action_description = action_info['action_description']
            action_path = action_info['action_path']
            action_length = action_info['action_length']
            skeleton_path = action_info['skeleton_path']
            keyframes = action_info['keyframes']
        except:
            return fail_api('动作信息缺失，出现错误！')

        try:
            skeleton_list = np.load('.' + skeleton_path)
        except:
            return fail_api(msg='找不到动作骨架')
        try:
            with open('.' + icon_path.replace('_uploads/course_action/videos',
                                              current_app.config.get("UPLOADED_ACTION_DEST")),
                      'rb') as f:
                image_data = f.read()
        except FileNotFoundError:
            return fail_api(msg="找不到动作封面")

        action = ActionInfo(course_id=course_id,
                            action_name=action_name,
                            action_icon=image_data,
                            action_description=action_description,
                            action_path=action_path,
                            action_length=action_length,
                            icon_path=action_icon_path,
                            skeleton_path=skeleton_path,
                            del_flag=0)
        db.session.add(action)
        db.session.commit()
        action_id = action.action_id
        # 创建一个 VideoCapture 对象
        cap = cv2.VideoCapture(
            '.' + action_path.replace('_uploads/course_action/videos', current_app.config.get("UPLOADED_ACTION_DEST")))
        # 获取视频的帧率
        fps = cap.get(cv2.CAP_PROP_FPS)
        for keyframe in keyframes:
            keyframe_time = time_to_milliseconds(keyframe['start'])
            if keyframe_time == -1:
                return fail_api('日期格式错误，动作关键帧添加失败')
            keyframe_time += int(keyframe['startMills'])
            keyframe_description = keyframe['keyframe_description']
            keyframe_focus = keyframe['keyframe_focus']
            # 获取动作中的十个关注点，并存入数组中
            focus = [keyframe_focus['left-shoulder'],
                     keyframe_focus['left-elbow'],
                     keyframe_focus['left-wrist'],
                     keyframe_focus['left-foot'],
                     keyframe_focus['left-knee'],
                     keyframe_focus['right-shoulder'],
                     keyframe_focus['right-elbow'],
                     keyframe_focus['right-wrist'],
                     keyframe_focus['right-foot'],
                     keyframe_focus['right-knee']]
            #  把十个bool值转为二进制存储
            if len(focus) != 10:
                return fail_api(msg="关注点信息错误，动作关键帧添加失败")
            keyframe_focus = bools_to_bin(focus)
            if 'skeleton' in keyframe:
                keyframe_skeleton = np.array(keyframe['skeleton']).tobytes()
            else:
                keyframe_skeleton = get_pose_at_time(skeleton_list=skeleton_list, time_ms=keyframe_time,
                                                     fps=fps).tobytes()
            # keyframe_skeleton = np.array(keyframe['skeleton']).tobytes()
            keyframe = KeyframeInfo(action_id=action_id,
                                    keyframe_time=keyframe_time,
                                    keyframe_description=keyframe_description,
                                    keyframe_focus=keyframe_focus,
                                    keyframe_skeleton=keyframe_skeleton)
            db.session.add(keyframe)
        db.session.commit()
    return success_api()


@course_standard_bp.get('/edit/course/<int:course_id>')
def getEditCoursePage(course_id):
    course = CourseStandard.query.filter_by(course_id=course_id, del_flag=0).with_entities(
        CourseStandard.course_id,
        CourseStandard.course_name,
        CourseStandard.course_description,
        CourseStandard.course_loadtime,
        CourseStandard.course_updatetime,
        CourseStandard.icon_path).one_or_none()
    if not course:
        return fail_api(msg="找不到课程信息")

    actions = ActionInfo.query.filter_by(course_id=course_id, del_flag=0).with_entities(ActionInfo.course_id,
                                                                                        ActionInfo.action_id,
                                                                                        ActionInfo.action_name,
                                                                                        ActionInfo.action_description,
                                                                                        ActionInfo.action_path,
                                                                                        ActionInfo.action_length,
                                                                                        ActionInfo.action_loadtime,
                                                                                        ActionInfo.action_updatetime,
                                                                                        ActionInfo.icon_path,
                                                                                        ActionInfo.skeleton_path).all()
    actions = model_to_dicts(schema=ActionSchema, data=actions)
    for action in actions:
        keyframes = KeyframeInfo.query.filter_by(action_id=action['action_id']).with_entities(KeyframeInfo.action_id,
                                                                                              KeyframeInfo.keyframe_id,
                                                                                              KeyframeInfo.keyframe_time,
                                                                                              KeyframeInfo.keyframe_description,
                                                                                              KeyframeInfo.keyframe_focus).all()
        frames = model_to_dicts(schema=KeyframeInfoSchema, data=keyframes)
        for frame in frames:
            bools = bin_to_bools(frame['keyframe_focus'])
            frame['keyframe_focus'] = {
                'left-shoulder': bools[0],
                'left-elbow': bools[1],
                'left-wrist': bools[2],
                'left-foot': bools[3],
                'left-knee': bools[4],
                'right-shoulder': bools[5],
                'right-elbow': bools[6],
                'right-wrist': bools[7],
                'right-foot': bools[8],
                'right-knee': bools[9]
            }
            frame['start'] = ms_to_time(frame['keyframe_time'])
            frame['startMills'] = frame['keyframe_time'] % 1000
        action['keyframes'] = frames

    return render_template('admin/course/action_standard/edit.html',
                           courseStandard=course,
                           actions=actions)


@course_standard_bp.get('/edit/action/<int:action_id>')
def getEditActionPage(action_id):
    action = ActionInfo.query.filter_by(action_id=action_id, del_flag=0).with_entities(ActionInfo.course_id,
                                                                                       ActionInfo.action_id,
                                                                                       ActionInfo.action_name,
                                                                                       ActionInfo.action_description,
                                                                                       ActionInfo.action_path,
                                                                                       ActionInfo.action_length,
                                                                                       ActionInfo.action_loadtime,
                                                                                       ActionInfo.action_updatetime,
                                                                                       ActionInfo.icon_path).one_or_none()
    if not action:
        return fail_api(msg="找不到动作信息")

    keyframes = KeyframeInfo.query.filter_by(action_id=action_id).with_entities(KeyframeInfo.action_id,
                                                                                KeyframeInfo.keyframe_id,
                                                                                KeyframeInfo.keyframe_time,
                                                                                KeyframeInfo.keyframe_description,
                                                                                KeyframeInfo.keyframe_focus).all()
    frames = model_to_dicts(schema=KeyframeInfoSchema, data=keyframes)
    for frame in frames:
        bools = bin_to_bools(frame['keyframe_focus'])
        frame['keyframe_focus'] = {
            'left-shoulder': bools[0],
            'left-elbow': bools[1],
            'left-wrist': bools[2],
            'left-foot': bools[3],
            'left-knee': bools[4],
            'right-shoulder': bools[5],
            'right-elbow': bools[6],
            'right-wrist': bools[7],
            'right-foot': bools[8],
            'right-knee': bools[9]
        }
        frame['start'] = ms_to_time(frame['keyframe_time'])
        frame['startMills'] = frame['keyframe_time'] % 1000

    return render_template('admin/course/action_standard/action/edit.html', action=action, keyframes=frames)


@course_standard_bp.get('/edit/action')
def getEditActionPage2():
    return render_template('admin/course/action_standard/action/edit_2.html')


@course_standard_bp.post('/edit/course')
def submitCourseEdit():
    data = request.json
    course_id = data['course_id']
    icon_path = data['course_icon']
    course_name = data['course_name']
    course_description = data['course_description']
    course_deleted = data['delete_list']
    action_infos = data['action_infos']

    courseStandard = CourseStandard.query.filter_by(course_id=course_id, del_flag=0).one_or_none()
    if not courseStandard:
        return fail_api(msg="找不到课程")
    if not courseStandard.icon_path == icon_path:
        try:
            with open('.' + icon_path.replace('_uploads/course_action/videos',
                                              current_app.config.get("UPLOADED_ACTION_DEST")),
                      'rb') as f:
                image_data = f.read()
                courseStandard.course_icon = image_data
                courseStandard.icon_path = icon_path
        except FileNotFoundError:
            return fail_api(msg="课程封面不存在")

    courseStandard.course_name = course_name
    courseStandard.course_description = course_description
    courseStandard.course_updatetime = datetime.now()

    # 第一遍遍历，先处理新增的动作
    for action_info in action_infos:
        if 'action_id' not in action_info or action_info['action_id'] == -1:
            action_icon = action_info['action_icon']
            action_name = action_info['action_name']
            action_description = action_info['action_description']
            action_path = action_info['action_path']
            action_length = action_info['action_length']
            skeleton_path = action_info['skeleton_path']
            keyframes = action_info['keyframes']
            try:
                skeleton_list = np.load('.' + skeleton_path)
            except:
                return fail_api(msg='找不到骨架参数')
            try:
                with open('.' + action_icon.replace('_uploads/course_action/videos',
                                                    current_app.config.get("UPLOADED_ACTION_DEST")),
                          'rb') as f:
                    image_data = f.read()
            except FileNotFoundError:
                return fail_api(msg="课程封面不存在")
            action = ActionInfo(course_id=course_id,
                                action_name=action_name,
                                action_icon=image_data,
                                action_description=action_description,
                                action_path=action_path,
                                action_length=action_length,
                                icon_path=action_icon,
                                skeleton_path=skeleton_path)
            db.session.add(action)
            db.session.commit()
            action_id = action.action_id

            # 下面处理动作的关键帧
            # 创建一个 VideoCapture 对象
            cap = cv2.VideoCapture(
                '.' + action_path.replace('_uploads/course_action/videos',
                                          current_app.config.get("UPLOADED_ACTION_DEST")))
            # 获取视频的帧率
            fps = cap.get(cv2.CAP_PROP_FPS)

            for keyframe in keyframes:
                keyframe_description = keyframe['keyframe_description']
                keyframe_focus = keyframe['keyframe_focus']
                # 获取动作中的十个关注点，并存入数组中
                focus = [keyframe_focus['left-shoulder'],
                         keyframe_focus['left-elbow'],
                         keyframe_focus['left-wrist'],
                         keyframe_focus['left-foot'],
                         keyframe_focus['left-knee'],
                         keyframe_focus['right-shoulder'],
                         keyframe_focus['right-elbow'],
                         keyframe_focus['right-wrist'],
                         keyframe_focus['right-foot'],
                         keyframe_focus['right-knee']]
                #  把十个bool值转为二进制存储
                if len(focus) != 10:
                    return fail_api(msg="关注点信息错误，动作关键帧添加失败")
                keyframe_focus = bools_to_bin(focus)
                keyframe_time = time_to_milliseconds(keyframe['start']) + int(keyframe['startMills'])
                if 'skeleton' in keyframe:
                    keyframe_skeleton = np.array(keyframe['skeleton']).tobytes()
                else:
                    keyframe_skeleton = get_pose_at_time(skeleton_list=skeleton_list, time_ms=keyframe_time,
                                                         fps=fps).tobytes()

                frame = KeyframeInfo(action_id=action_id,
                                     keyframe_time=keyframe_time,
                                     keyframe_description=keyframe_description,
                                     keyframe_focus=keyframe_focus,
                                     keyframe_skeleton=keyframe_skeleton)
                db.session.add(frame)

    # 第二遍遍历，修改更新了信息的动作
    for action_info in action_infos:
        if 'action_id' in action_info and action_info['action_id'] != -1 and action_info['has_change']:
            # 从字典中获取信息
            action_id = action_info['action_id']
            action_icon = action_info['icon_path']
            action_name = action_info['action_name']
            action_description = action_info['action_description']
            action_path = action_info['action_path']
            action_length = action_info['action_length']
            skeleton_path = action_info['skeleton_path']
            if 'delete_list' in action_info:
                delete_list = action_info['delete_list']
            else:
                delete_list = []
            keyframes = action_info['keyframes']

            # 查找动作
            action = ActionInfo.query.filter_by(action_id=action_id, del_flag=0).one_or_none()
            if not action:
                return fail_api(msg="找不到动作信息")

            try:
                skeleton_list = np.load('.' + skeleton_path)
                print(skeleton_path)
            except:
                return fail_api(msg='找不到骨架参数')

            # 更新动作信息
            try:
                with open('.' + action_icon.replace('_uploads/icons', current_app.config.get("UPLOADED_ICONS_DEST")),
                          'rb') as f:
                    image_data = f.read()
                    action.action_icon = image_data
                    action.icon_path = action_icon
            except FileNotFoundError:
                return fail_api(msg="课程封面不存在")
            action.action_name = action_name
            action.action_description = action_description
            action.action_path = action_path
            action.action_length = action_length
            action.skeleton_path = skeleton_path
            action.action_updatetime = datetime.now()

            # 下面处理动作的关键帧
            # 创建一个 VideoCapture 对象
            cap = cv2.VideoCapture(
                '.' + action_path.replace('_uploads/course_action/videos',
                                          current_app.config.get("UPLOADED_ACTION_DEST")))
            # 获取视频的帧率
            fps = cap.get(cv2.CAP_PROP_FPS)

            # 移除被删除的关键帧
            deleted_frames = KeyframeInfo.query.filter(KeyframeInfo.keyframe_id.in_(delete_list)).all()
            for point in deleted_frames:
                db.session.delete(point)

            # 遍历传入的关键帧，如果是已经存在数据库中的则更新，没存在数据库中的则插入新的数据项
            for keyframe in keyframes:
                keyframe_description = keyframe['keyframe_description']
                keyframe_focus = keyframe['keyframe_focus']
                # 获取动作中的十个关注点，并存入数组中
                focus = [keyframe_focus['left-shoulder'],
                         keyframe_focus['left-elbow'],
                         keyframe_focus['left-wrist'],
                         keyframe_focus['left-foot'],
                         keyframe_focus['left-knee'],
                         keyframe_focus['right-shoulder'],
                         keyframe_focus['right-elbow'],
                         keyframe_focus['right-wrist'],
                         keyframe_focus['right-foot'],
                         keyframe_focus['right-knee']]
                #  把十个bool值转为二进制存储
                if len(focus) != 10:
                    return fail_api(msg="关注点信息错误，动作关键帧添加失败")
                keyframe_focus = bools_to_bin(focus)
                keyframe_time = time_to_milliseconds(keyframe['start']) + int(keyframe['startMills'])
                if 'skeleton' in keyframe:
                    keyframe_skeleton = np.array(keyframe['skeleton']).tobytes()
                else:
                    keyframe_skeleton = get_pose_at_time(skeleton_list=skeleton_list, time_ms=keyframe_time,
                                                         fps=fps).tobytes()
                if 'keyframe_id' in keyframe:
                    frame = KeyframeInfo.query.filter_by(keyframe_id=keyframe['keyframe_id']).one_or_none()
                    frame.keyframe_time = keyframe_time
                    frame.keyframe_description = keyframe_description
                    frame.keyframe_focus = keyframe_focus
                    frame.keyframe_skeleton = keyframe_skeleton
                else:
                    frame = KeyframeInfo(action_id=action_id,
                                         keyframe_time=keyframe_time,
                                         keyframe_description=keyframe_description,
                                         keyframe_focus=keyframe_focus,
                                         keyframe_skeleton=keyframe_skeleton)
                    db.session.add(frame)

    # 最后处理删除的课程
    deleted_actions = ActionInfo.query.filter(ActionInfo.action_id.in_(course_deleted)).all()
    for action in deleted_actions:
        action.del_flag = 1
    db.session.commit()
    return success_api()


@course_standard_bp.delete('/remove/<int:course_id>')
def remove(course_id):
    courseStandard = CourseStandard.query.filter_by(course_id=course_id, del_flag=0).one_or_none()
    if not courseStandard:
        return fail_api(msg="该课程不存在")
    actions = ActionInfo.query.filter_by(course_id=course_id).all()
    for action in actions:
        action.del_flag = 1
    courseStandard.del_flag = 1
    db.session.commit()
    return success_api(msg="删除成功")


@course_standard_bp.delete('/batchRemove')
def batch_remove():
    try:
        ids = list(map(int, request.form.getlist('ids[]')))
    except:
        return fail_api(msg="找不到参数")
    courses = CourseStandard.query.filter(CourseStandard.course_id.in_(ids)).all()
    for course in courses:
        course.del_flag = 1
        actions = ActionInfo.query.filter_by(course_id=course.course_id).all()
        for action in actions:
            action.del_flag = 1
    db.session.commit()
    return success_api("批量删除成功")


# 获取成绩页面
@course_standard_bp.get('/result')
def getResultPage():
    return render_template('admin/course/action_standard/result.html')

@course_standard_bp.get('/result/detail/<int:student_id>')
def result_details(student_id):
    # 获取请求参数
    action_Name = xss_escape(request.args.get('action_Name', type=str))

    # 查询参数构造
    mf = ModelFilter()
    if action_Name:
        mf.contains(field_name="action_Name", value=action_Name)

    results = StandardResult.query.order_by('train_time').filter_by(student_id=student_id).layui_paginate()
    results_dict = model_to_dicts(schema=StandardResultSchema, data=results.items)
    for result in results_dict:
        action = ActionInfo.query.filter_by(action_id=result['action_id']).with_entities(ActionInfo.course_id,
                                                                                         ActionInfo.action_id,
                                                                                         ActionInfo.action_name,
                                                                                         ActionInfo.action_description).one_or_none()
        if action is not None:
            result['action_name'] = action.action_name
            course = CourseStandard.query.filter_by(course_id=action.course_id).with_entities(CourseStandard.course_id,
                                                                                              CourseStandard.course_name,
                                                                                              CourseStandard.course_description).one_or_none()
            if course is not None:
                result['course_name'] = course.course_name
                result['course_description'] = course.course_description
    count = results.total
    return render_template('admin/course/action_standard/result_detail.html', data=results_dict, count=count)


@course_standard_bp.delete('/result/remove/<int:grade_id>')
def result_remove(grade_id):
    result = StandardResult.query.filter_by(grade_id=grade_id).delete()
    db.session.commit()
    return success_api()


@course_standard_bp.delete('/result/batchRemove')
def result_batch_remove():
    try:
        ids = list(map(int, request.form.getlist('ids[]')))
    except:
        return fail_api(msg="找不到参数")
    results = StandardResult.query.filter(StandardResult.grade_id.in_(ids)).delete()
    db.session.commit()
    return success_api()


# 把包含10个布尔值的数组转为数字存储
def bools_to_bin(bool_list):
    # 确保输入的是 10 个 bool 值
    if len(bool_list) != 10:
        raise ValueError("Input list must contain exactly 10 boolean values")
    bin_str = ''
    for val in bool_list:
        bin_str += '1' if val else '0'
    return int(bin_str, 2)


#  把数组转为10个布尔值
def bin_to_bools(bin_num):
    # 确保输入的是 10 位二进制数
    if bin_num > 1023 or bin_num < 0:
        raise ValueError("Input number must be a 10-bit binary number")
    bin_str = format(bin_num, '010b')
    return [bool(int(b)) for b in bin_str]


# 时分秒时间（HH:mm:ss）转毫秒
def time_to_milliseconds(time_str):
    try:
        # 将时间字符串解析为时间对象
        time_obj = datetime.strptime(time_str, "%H:%M:%S")
        # 计算时间对象的总毫秒数
        total_milliseconds = (time_obj - datetime(1900, 1, 1)) // timedelta(milliseconds=1)
        return total_milliseconds
    except:
        return -1


# 把毫秒转为 HH:mm:ss
def ms_to_time(ms):
    # 将毫秒转换为秒
    seconds = ms / 1000.0
    # 使用timedelta创建一个时间间隔
    td = timedelta(seconds=seconds)
    # 创建一个零时间
    zero = datetime(1, 1, 1)
    # 添加时间间隔
    time = zero + td
    # 格式化时间并返回
    return time.strftime("%H:%M:%S")


# 根据毫秒获取对应的人体骨架
def get_pose_at_time(skeleton_list, time_ms, fps):
    # 将毫秒转换为秒，然后乘以帧率得到帧编号
    frame_number = int(time_ms / 1000.0 * fps)
    # 检查帧编号是否在列表的索引范围内
    if 0 <= frame_number < len(skeleton_list):
        return skeleton_list[frame_number]
    else:
        return None


@course_standard_bp.get('/result/detail/detail/<int:grade_id>')
def result_detail_details(grade_id):
    result = StandardResult.query.filter_by(grade_id=grade_id).one_or_none()
    if result is None:
        return fail_api(msg="找不到该动作信息！")

    course = CourseStandard.query.filter_by(course_id=result.course_id).with_entities(CourseStandard.course_id,
                                                                                      CourseStandard.course_name,
                                                                                      CourseStandard.course_description,
                                                                                      CourseStandard.course_loadtime,
                                                                                      CourseStandard.course_updatetime).one_or_none()
    action = ActionInfo.query.filter_by(action_id=result.action_id).with_entities(ActionInfo.course_id,
                                                                                  ActionInfo.action_id,
                                                                                  ActionInfo.action_name,
                                                                                  ActionInfo.action_description,
                                                                                  ActionInfo.action_path,
                                                                                  ActionInfo.action_length,
                                                                                  ActionInfo.action_loadtime,
                                                                                  ActionInfo.action_updatetime,
                                                                                  ActionInfo.icon_path).one_or_none()
    police = PoliceModels.query.filter_by(id=result.student_id).one_or_none()

    return render_template('admin/course/action_standard/result_detail_detail.html',
                           result=result,
                           course=course,
                           action=action,
                           police=police)


@course_standard_bp.delete('/result/detail/remove/<int:grade_id>')
def result_detail_remove(grade_id):
    result = StandardResult.query.filter_by(grade_id=grade_id).delete()
    db.session.commit()
    return success_api()


@course_standard_bp.delete('/result/detail/batchRemove')
def result_detail_batch_remove():
    try:
        ids = list(map(int, request.form.getlist('ids[]')))
    except:
        return fail_api(msg="找不到参数")
    results = StandardResult.query.filter(StandardResult.grade_id.in_(ids)).delete()
    db.session.commit()
    return success_api()
